import React, {Component} from 'react'
import { withRouter } from 'dva/router'
import styles from './ConfirmOrder.less'
import { Button, message } from 'antd'
import reduce from 'lodash/reduce'
import { buy } from '@/services/course'
import { buy as buyBook } from '@/services/book'
import { formatUrlQueryToMap } from '@/utils/utils'
import { connect } from 'dva'
import { GET_COURSE_DETAIL } from "../../actions/course"
import { GET_BOOK_DETAIL } from "../../actions/book"
import { GET_PAY_ORDER_DETAIL } from "../../actions/order"


@connect(({ course, book, order, address }) => ({
  course,
  book,
  order,
  address
}))
class ConfirmOrder extends Component {
  constructor(props){
    super(props)
    this.state = {
      activePayType: "wechat"
    }
  }

  componentDidMount() {
    this.getDetails()
  }

  getCourseDetail() {
    const {dispatch, match: {params: {id}}} = this.props
    dispatch(GET_COURSE_DETAIL(id))
  }

  getBookDetail() {
    const {dispatch, match: {params: {id}}} = this.props
    dispatch(GET_BOOK_DETAIL(id))
  }

  setPayType(type) {
    this.setState({
      activePayType: type
    })
  }

  getDetails() {
    const {match: { url }} = this.props
    const alipayParams = formatUrlQueryToMap('out_trade_no')
    const { out_trade_no = '' } = alipayParams
    if (out_trade_no) {
      // 支付成功回调
      const { dispatch } = this.props
      dispatch(GET_PAY_ORDER_DETAIL(out_trade_no))
    } else {
      url.includes('/course/order') ? this.getCourseDetail() : this.getBookDetail()
    }
  }

  // 判断有无订单号
  getRenderDetail() {
    const {course, book, order } = this.props
    const alipayParams = formatUrlQueryToMap('out_trade_no')
    const { out_trade_no = '' } = alipayParams
    const { match: { url } } = this.props
    let detail = url.includes('/course/order') ? course.detail : book.detail
    if (out_trade_no) {
      const { payDetail: { digest, items, payChannel, status } } = order
      detail = {
        title: digest,
        price: reduce(items, (sum, next) => {
          return sum + (next['productPrice'] * next['productCount'])
        }, 0),
        payChannel,
        status
      }
    }
    return detail
  }

  // 订单状态
  orderStatusMessage(detail) {
    const { match: { url, params: {id} } } = this.props
    const { status = '' } = detail
    if (status == 'paid') {
      message.destroy()
      message.success('支付成功')
      setTimeout(() => {
        url.includes('/course/order') ? window.location.href = `/course/${id}` : window.location.href = `/book/${id}`
      }, 1000)
    }
  }

  pay(id) {
    const {showAddress, address: { addressList }, book: {detail}} = this.props
    const { activePayType } = this.state
    if (showAddress) {
      // 书籍购买
      // 是否有默认地址
      let hasDefaultAddress = addressList.find(item => item.isDefault)
      if (hasDefaultAddress) {
        let { address, mobile, addressee } = hasDefaultAddress
        let books = [{id: detail.id, amount: 1}]
        buyBook({
          channel: activePayType,
          source: 'web',
          returnUrl: window.location.href,
          address,
          mobile,
          addressee,
          books
        }).then(res => {
          if (res.data.code == 0) {
            let payWindow = window.open();
            payWindow.document.write(res.data.data)
          } else {
            message.error(res.data.msg)
          }
        })
      } else {
        message.error('请添加收获地址')
      }
    } else {
      // 购买
      buy(id, {
        channel: activePayType,
        source: 'web',
        returnUrl: window.location.href
      }).then(res => {
        if (res.data.code == 0) {
          let payWindow = window.open();
          payWindow.document.write(res.data.data)
        } else {
          message.error(res.data.msg)
        }
      })
    }
  }

  render() {
    let { activePayType } = this.state
    const { match: { url } } = this.props
    const detail = this.getRenderDetail()
    this.orderStatusMessage(detail)
    return (
      <div className={styles.confirmOrderContainer}>
          <div className={styles.textContainer}>
            <h2 className={styles.title}>购买商品内容</h2>
            <h3 className={styles.productTitle}>{detail.title}</h3>
            <div className={styles.productContainer}>
              <p>¥ {(detail.price / 100).toFixed(2)}</p>
              {
                url.startsWith('/book') && (
                  detail.amount ? <p>X {detail.amount}</p>: <p>X 1</p>
                )
              }
            </div>
          </div>
          <div className={styles.textContainer}>
            <h2 className={styles.title}>选择支付方式</h2>
            <div className={styles.imgContainer}>
              {
                detail.payChannel ?
                <>
                  <img className={detail.payChannel == 'wechat'? styles.payTypeActive: ''} src={require('../../assets/wx.jpg')}/>
                  <img className={detail.payChannel == 'alipay'? styles.payTypeActive: ''} src={require('../../assets/zfb.jpg')}/>
                </> :
                  <>
                    <img className={activePayType == 'wechat'? styles.payTypeActive: ''} onClick={(e)=>{this.setPayType.call(this, 'wechat')}} src={require('../../assets/wx.jpg')}/>
                    <img className={activePayType == 'alipay'? styles.payTypeActive: ''} onClick={this.setPayType.bind(this,'alipay')} src={require('../../assets/zfb.jpg')}/>
                  </>
              }
            </div>
          </div>
          <div className={styles.textContainer}>
            <h2 className={styles.title}>支付金额</h2>
            <div className={styles.priceContainer}>
              <p>¥ {(detail.price / 100).toFixed(2)}</p>
              <Button type="primary" onClick={this.pay.bind(this, detail.id)} disabled={detail.payChannel}>
                付款
              </Button>
            </div>
          </div>
      </div>
    );
  }
}

export default withRouter(ConfirmOrder);